/*
 * Playdom, Inc. (c) 2009 - 2010 All Rights Reserved
 */
package com.mind.core.util;

import java.util.TimeZone;


/**
 * JotTime is usually System.currentTimeMillis(), this is a very thin wrapper.
 * 
 * However, if you startDebugMode it for debug mode then it keeps track of how much time was spent while all the threads
 * were halted. It's a debug thang.
 * 
 * @author alanwootton
 * 
 */
public class JotTime {
    private static TimeWatcher watcher = null;// singleton
    private static Thread watcherThread = null;// singleton

    public static void startDebugMode() {
        if (watcher == null) {
            running = true;
            watcher = new TimeWatcher();
            watcherThread = new Thread(watcher, "JotTime.TimeWatcher");
            watcherThread.start();
        }
    }

    public static void stopDebugMode() {
        if (watcher != null) {
            running = false;
            try {
                watcherThread.join();
            } catch (InterruptedException e) {
            }
            watcher = null;
            watcherThread = null;
        }
    }

    public static boolean isDebugMode() {
        return watcher != null;
    }

    public static boolean running = true;

    public static final long get() {
        if (watcher == null){
        	return System.currentTimeMillis();
        }
        else
            return watcher.get();
    }

    public static final long getTimeZoneOffset(){
    	return TimeZone.getDefault().getOffset(System.currentTimeMillis());
    }
    
    // when in debug mode the time might pass a little slow
    // when you are stepping in the debugger time doesn't pass at all.
    private static class TimeWatcher implements Runnable {
        static final int sleeptime = 1;

        private long theTime = System.currentTimeMillis();

        public void run() {
            while (running) {
                try {
                    Thread.sleep(sleeptime);
                } catch (InterruptedException e) {
                }
                theTime += sleeptime;
            }
        }

        long get() {
            return theTime;
        }
    }

    public static void teleport2future(long howmuch) {
        if (watcher != null) {
            watcher.theTime += howmuch;
        }
    }

}
